/*===============================================
 *   文件名称：udp_server.c
 *   创 建 者：     
 *   创建日期：2024年09月19日
 *   描    述：
 ================================================*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>


int main(int argc, char *argv[])
{ 
    if(argc < 3){
        printf("Usage:%s <IP> <PORT>\n", argv[0]);
        return -1;
    }

    //创建数据报套接字
    int sfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(-1 == sfd){
        perror("socket");
        return -1;
    }

    //绑定IP PORT
    struct sockaddr_in saddr;
    saddr.sin_family      = AF_INET;
    saddr.sin_port        = htons(atoi(argv[2]));
    saddr.sin_addr.s_addr = inet_addr(argv[1]);

    char buf[1024], pic_len[5];
    socklen_t len = sizeof saddr;

    int size;
    int fd = open("1.png", O_WRONLY|O_CREAT, 0777);
    if(-1 == fd){
        perror("open");
        return -1;
    }
    while(1){
        fgets(buf, 1024, stdin);
        if(-1 == sendto(sfd, buf, 1024, 0, (void *)&saddr, len)){
            perror("sendto");
            return -1;
        }
        if(-1 == recvfrom(sfd, pic_len, 5, MSG_WAITALL, (void *)&saddr, &len)){
            perror("recvfrom");
            break;
        }
        if(0 == strcmp(pic_len, "no")){
            continue;
        }
        while(1){
            if(-1 == recvfrom(sfd, pic_len, 5, MSG_WAITALL, (void *)&saddr, &len)){
                perror("recvfrom");
                break;
            }
            size = atoi(pic_len);
            printf("size:%d\n", size);
            if(0 == size){
                puts("over");
                break;
            }
            if(-1 == recvfrom(sfd, buf, size, MSG_WAITALL, (void *)&saddr, &len)){
                perror("recvfrom");
                break;
            }
            write(fd, buf, size);
        }
    }
    return 0;
} 
